/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.inmp.conf;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.sinodata.bsm.inmp.util.WebServiceUtil;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-11-29 下午7:03:06          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class RTPerfCache {

    private static final Logger logger = Logger.getLogger(RTPerfCache.class);

    public static RTPerfCache instance = null;

    Map<String, String> perfMap = new HashMap<String, String>();

    private static final Long INTERVAL_TIME = 5 * 60 * 1000L;

    //key:jobid ,value:获取到值的时间
    private Map<String, Date> timeMap = new HashMap<String, Date>();

    private static Object _lock = new Object();

    private RTPerfCache() {
        logger.info("[TIP]\tinit");
    }

    /**
     * 
     * @return
     */
    public static synchronized RTPerfCache getInstance() {
        if (instance == null) {
            instance = new RTPerfCache();
        }
        return instance;
    }

    /**
     * 缓存一个值
     * @param key
     * @param value
     */
    public void put(String key, String value) {
        perfMap.put(key, value);
    }

    /**
     * 缓存一个网络设备的实时性能
     * @param jobId
     * @param date
     */
    private void cache(String jobId, Date date) {
        if (timeMap.get(jobId) != null) {
            return;
        }
        List<String[]> list = WebServiceUtil.getInstance().getRealTimePerf(jobId);
        if (list != null) {
            for (String[] stry : list) {
                put(stry[0], stry[1]);
            }
        }
        timeMap.put(jobId, date);
    }

    /**
     * 获取一个资源的值 
     * 如果值为空   或值已经过期 则从新取
     * @param key
     * @return
     */
    public String get(String key) {
        if (key == null || key.length() == 0) {
            return null;
        }
        Date now = Calendar.getInstance().getTime();
        String value = perfMap.get(key);
        String jobId = key.split("[,]")[0];
        Date date = timeMap.get(jobId);
        if (value != null && (now.getTime() - date.getTime() < INTERVAL_TIME)) {
            return value;
        } else {
            synchronized (_lock) {
                cache(jobId, now);
            }
            value = perfMap.get(key);
        }
        return value;
    }

}
